/**
 * 对 Axios 库的二次封装
 *
 * author: zengsun
 * date: 2021-5-5
 */

import axios from "axios";
import { notEmpty, stringify } from "./utils";
import createEmitter from "./emitter";

const request = (url, options = {}) => {
  const { headers = {}, method = "GET", data = {} } = options;
  if (
    headers["Content-Type"] === "application/x-www-form-urlencoded" &&
    notEmpty(data)
  ) {
    options.data = stringify(data);
  }
  options.url = url;
  options.method = method;
  return request.http.request(options);
};

const httpEvent = createEmitter(),
  errorMessage = {
    401: "未验证的用户",
  };
const createHttp = (options) => {
  const http = axios.create(options);
  // axios 请求拦截
  http.interceptors.request.use((config) => {
    // 触发请求事件
    httpEvent.emit("request", config);
    return config;
  });
  // axios 响应拦截
  http.interceptors.response.use(
    (response) => {
      // 触发响应事件
      httpEvent.emit("response", response);
      return response;
    },
    (error) => {
      // 触发错误事件
      const { status, data } = error.response;
      if (status in errorMessage) {
        httpEvent.emit("error", {
          status,
          data,
          message: errorMessage[status],
        });
        return Promise.resolve(error.response);
      }
      httpEvent.emit("error", { status: 0, data: {}, message: "未知错误" });
      return Promise.reject(error);
    }
  );
  request.http = http;
};
createHttp({ timeout: 1000 });

// 作为一个 vue 插件
request.install = (app) => {
  app.config.globalProperties.$request = request;
};

export { request, createHttp, httpEvent };

export default request;
